import os
import time
from datetime import datetime

import allure
import yaml
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from . import data_path
from ..utils.Loguru import logger
class base_page(object):
    def __init__(self,driver):

        chromeOptions = webdriver.ChromeOptions()
        chromeOptions.add_argument('--start-maximized')
        chromeOptions.add_experimental_option('excludeSwitches', ['enable-automation'])
        chromeOptions.add_experimental_option('useAutomationExtension', False)
        chromeOptions.add_argument("--disable-blink-features=AutomationControlled")

        if driver == None:
            self.driver = webdriver.Chrome(chromeOptions)
        else:
            self.driver = driver
        # self.driver = webdriver.Chrome(chromeOptions)
        self.wait = WebDriverWait(self.driver, 30)
        self.actions = ActionChains(driver)
        # self.driver.implicitly_wait(15)


    def find_ele_is_presence(self,locator):
        a,b = locator
        logger.info(f'通过方式：{a},查找路径为{b}的元素')
        try:
            ele = self.wait.until(EC.presence_of_element_located(locator=locator))
            logger.info(f'找到元素')
            return ele
        except Exception as e:
            logger.debug(f'元素查找错误：{e}')
            raise e

    def find_eles_is_presence(self,locator):
        a, b = locator
        logger.info(f'通过方式：{a},查找路径为{b}的元素列表')
        try:

            ele_list = self.wait.until(EC.presence_of_all_elements_located(locator=locator))
            logger.info(f'找到元素列表')
            return ele_list
        except Exception as e:
            logger.debug(f'元素查找错误：{e}')
            raise e

    def find_ele_is_clickable(self,locator):
        a,b = locator
        logger.info(f'通过方式：{a},查找路径为{b}的元素')
        try:
            ele = self.wait.until(EC.element_to_be_clickable(locator))
            logger.info(f'找到元素')
            return ele
        except Exception as e:
            logger.debug(f'元素查找错误：{e}')
            raise e

    def get_faker_number(self):
        import faker
        logger.info('生成模拟数据')

        fake = faker.Faker(locale='zh_CN')  # 初始化，指定生成中文格式数据
        phone = fake.phone_number()  # 生成一条电话号码
        return phone
    def get_faker_name(self):
        import faker
        logger.info('生成模拟数据')

        fake = faker.Faker(locale='zh_CN')  # 初始化，指定生成中文格式数据
        name = fake.name_female()  # 生成一条电话号码
        return name

    def get_faker_account(self):
        import faker
        logger.info('生成模拟数据')

        fake = faker.Faker(locale='zh_CN')  # 初始化，指定生成中文格式数据
        name = fake.random_number(10) # 生成一条电话号码
        return name

    def js_click(self,ele):

        self.driver.execute_script("arguments[0].click();", ele)

    def create_path_if_not_exists(self,path):
        logger.info(f'判断路径{path}是否存在')
        if not os.path.exists(path):
            os.makedirs(path)
            print(f"Created directory at {path}")
            logger.info(f'路径{path}不存在，已创建')
        else:
            print(f"Directory already exists at {path}")
            logger.info(f'路径{path}已创建')



    def screen_shot(self):
        logger.info(f'发生异常，生成页面截图')
        time_stamp = int(time.time())
        # 将时间戳转换为datetime对象
        dt_object = datetime.fromtimestamp(time_stamp)

        formatted_date = dt_object.strftime('%Y-%m-%d')
        # 格式化datetime对象为年-月-日的字符串
        formatted_date1 = dt_object.strftime('%H时-%M分-%S秒')
        page_path = os.path.join(data_path,f'screen_shot/{formatted_date}')
        self.create_path_if_not_exists(page_path)
        screen_shot_path=os.path.join(page_path, f'异常时刻截图{formatted_date1}.png')
        self.driver.save_screenshot(screen_shot_path)
        # 添加图片到allure
        allure.attach.file(screen_shot_path, attachment_type=allure.attachment_type.PNG)

    #添加图片到allure
    def add_picture_to_allure(self,path):
        allure.attach.file("./pytest_study/image/pikaqiu.jpg", attachment_type=allure.attachment_type.JPG)

    def download_page_source(self):
        logger.info(f'发生异常，提取页面源码')

        time_stamp = int(time.time())
        # 将时间戳转换为datetime对象
        dt_object = datetime.fromtimestamp(time_stamp)

        # 格式化datetime对象为年-月-日的字符串
        formatted_date1 = dt_object.strftime('%H时-%M分-%S秒')

        print(formatted_date1)
        formatted_date = dt_object.strftime('%Y-%m-%d')
        page_path = os.path.join(data_path,f'page_source/{formatted_date}')
        page_source_path = os.path.join(page_path, f'异常时刻代码{formatted_date1}.txt')
        self.create_path_if_not_exists(page_path)
        # 添加图片到allure
        allure.attach(body= self.driver.page_source, name="test文本01", attachment_type=allure.attachment_type.TEXT)

        with open(page_source_path,'w') as f:
            f.write( self.driver.page_source)



    def auto_download_web_driver(self,web):
        # Selenium4.0以上版本使用该方法
        import os
        import shutil
        from selenium import webdriver
        from selenium.webdriver.chrome.service import Service
        from webdriver_manager.chrome import ChromeDriverManager


        # 指定驱动目标位置
        folder_path = os.path.join(data_path, f'driver_chrome')
        self.create_path_if_not_exists(folder_path)
        # 路径拼接
        file_path = os.path.join(folder_path, 'chromedriver.exe')

        # 使用ChromeDriverManager安装ChromeDriver，并获取驱动程序的路径
        download_driver_path = ChromeDriverManager().install()
        # 复制文件到目标位置
        shutil.copy(download_driver_path, file_path)
        logger.info(f'自动下载谷歌浏览器引擎到路径{file_path}')




    def login_get_cookie(self):
        # 构建要查找的子文件夹的路径
        logger.info('将cookie导入yaml存储')
        LOG_FILE = os.path.join(data_path, "cookie.yaml")
        # 检查子文件夹是否存在
        cookies = self.driver.get_cookies()
        with open(LOG_FILE,'w') as f:
            yaml.safe_dump(data=cookies, stream=f)



    def read_cookie(self):
        logger.info('读取cookie')
        LOG_FILE = os.path.join(data_path, "cookie.yaml")
        with open(LOG_FILE,'r') as f:
            cookies = yaml.safe_load(f)

        return cookies


    def is_not_file_empty(self,file_path):
        #文件存在且里面有东西返回true，否则返回false
        if not os.path.isfile(file_path):
            return False  # 或者你可以抛出一个异常，因为文件不存在
        return os.path.getsize(file_path) != 0



    def wait_web_ulr_change(self,url):
        self.wait.until(EC.url_changes(url))

    def jug_is_login(self):
        logger.info('正在判断是否登录成功企业微信')
        self.wait.until(EC.url_contains('https://work.weixin.qq.com/wework_admin/frame'))


    def clean_cookie(self):

        LOG_FILE = os.path.join(data_path, "cookie.yaml")
        with open(LOG_FILE, 'w') as f:
            logger.info('清除过期或无效的cookie信息')

    def box_scroll_to_down_find_eles(self,locator_box,locator_eles):
        n=1
        logger.info(f'开始往下滚动，查找元素{locator_eles}')
        box = self.find_ele_is_presence(locator_box)
        # document.querySelector('.page-content').scrollTo(0, 300)
        while True:
            # js='self.driver.execute_script("arguments[0].click();", ele)'
            try:
                return  self.find_eles_is_presence(locator_eles)
            except:
                self.driver.execute_script(f"arguments[0].scrollTo(0, {n * 100});", box)
                n += 1

    def send_input_file_path(self):
        file_path = os.path.join(data_path,'通讯录数据.xlsx')
        if not os.path.exists(file_path):
            logger.warning('-------data文件夹下没有通讯录数据.xlsx文件--------')
            return None
        else:
            logger.info(f'---------------将通讯录数据所在文件路径发送{file_path}--------------')
            return file_path


    def scroll_to_down_find_eles(self,locator_eles):
        '''
        window.scrollTo(0,100)
        window.scrollTo(0,document.body.scrollHeight)
        :param locator_eles:
        :return:
        '''
        n=1
        logger.info(f'开始往下滚动，查找元素{locator_eles}')

        # document.querySelector('.page-content').scrollTo(0, 300)
        while True:
            # js='self.driver.execute_script("arguments[0].click();", ele)'
            try:
                  # eles = self.find_eles_is_presence(locator_eles)
                  eles = self.driver.find_elements(locator_eles[0],locator_eles[1])
                  return eles
            except:
                # self.driver.execute_script(f"window.scrollTo(0, {n * 100});")
                # 向上滑动500像素
                self.driver.execute_script("window.scrollBy(0, 500)")

                n += 1



